//
//  CYWelcomeController.swift
//  CYSinaWB
//
//  Created by mac on 16/2/20.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage

class CYWelcomeController: UIViewController {
    override func loadView() {
        //自定义跟视图
        view = UIImageView(image: UIImage(named: "ad_background"))
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        startAnimation()
    }
    
    private func startAnimation() {
        //闭包动画  有弹簧效果
        let offset = -UIScreen.mainScreen().bounds.height + 160
        self.iconView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.98, initialSpringVelocity: 9.8, options: [], animations: { () -> Void in
            //提前更新界面
            self.view.layoutIfNeeded()
            }) { (_) -> Void in
                UIView.animateWithDuration(1.5, animations: { () -> Void in
                    self.welcomeLabel.alpha = 1
                    }, completion: { (_) -> Void in
                        print("it is ok")
//                        UIApplication.sharedApplication().keyWindow?.rootViewController = CYMainViewController()
                        NSNotificationCenter.defaultCenter().postNotificationName(KChooseRootVC, object: "welcome")
                })
        }
        
    }
    private func setUI() {
        view.addSubview(iconView)
        view.addSubview(welcomeLabel)
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            make.bottom.equalTo(view.snp_bottom).offset(-160)
            make.size.equalTo(CGSizeMake(90, 90))
            
        }
        welcomeLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(iconView.snp_centerX)
            make.top.equalTo(iconView.snp_bottom).offset(16)
        }
        welcomeLabel.alpha = 0
        iconView.sd_setImageWithURL(CYAccountViewModel.sharedViewModel.headImgURL)
        //头像圆角
        iconView.layer.cornerRadius = 45
        iconView.layer.masksToBounds = true
    }
    

    
    //懒加载两个视图
    private lazy var iconView: UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
    
    private lazy var welcomeLabel: UILabel = UILabel(text: (CYAccountViewModel.sharedViewModel.userName ?? "") + " welcome back", fontSize: 18, textColor: UIColor.darkGrayColor())
}
